package com.qys.livesMall.user.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.QysStringUtils;
import com.qys.livesMall.common.utils.bean.BeanProUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.framework.view.Paging;
import com.qys.livesMall.framework.view.QysPage;
import com.qys.livesMall.system.source.service.ISysConfigService;
import com.qys.livesMall.user.domain.dto.user.*;
import com.qys.livesMall.user.domain.entity.SysRole;
import com.qys.livesMall.user.domain.entity.SysUser;
import com.qys.livesMall.user.domain.entity.SysUserRole;
import com.qys.livesMall.user.domain.vo.user.SysUserVO;
import com.qys.livesMall.user.mapper.SysRoleMapper;
import com.qys.livesMall.user.mapper.SysUserMapper;
import com.qys.livesMall.user.mapper.SysUserRoleMapper;
import com.qys.livesMall.user.service.ISysRoleService;
import com.qys.livesMall.user.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author wanglei
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;


    @Autowired
    private SysUserRoleMapper userRoleMapper;



    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param search 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public QysPage<SysUserVO> selectUserList(SysUserSearch search) {
        Paging<SysUser> sPage = userMapper.search( new Paging<>(search));
        return QysPage.to(sPage, SysUserVO.class);
//        Page<SysUser> sPage = userMapper.selectUserList(new Page<>(search.pageNum, search.pageSize), search);
//        return QysPage.to(sPage, SysUserVO.class);
    }



    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUserVO selectUserById(Long userId) {
        SysUser user=userMapper.selectUserById(userId);
        SysUserVO vo=null;
        if (user!=null){
            vo=new SysUserVO();
            BeanProUtils.copyProperties(user,vo);
        }
        return vo;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }



    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameExist(String userName) {
        SysUser info = userMapper.selectUserByUserName(userName);
        return info!=null;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = user.getUserId()==null ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (info!=null && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId =  user.getUserId()==null ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (info!=null && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }


//    /**
//     * 校验用户是否有数据权限
//     *
//     * @param userId 用户id
//     */
//    @Override
//    public void checkUserDataScope(Long userId) {
//        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
//            SysUser user = new SysUser();
//            user.setUserId(userId);
//            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
//            if (StringUtils.isEmpty(users)) {
//                throw new ServiceException("没有权限访问用户数据！");
//            }
//        }
//    }

    /**
     * 新增保存用户信息
     *
     * @param addSysUser 用户信息
     * @return 结果
     */
    @Override
    public int insertUser(AddSysUser addSysUser) {

        SysUser sysUser=new SysUser();
        BeanProUtils.copyProperties(addSysUser,sysUser);
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        // 新增用户信息
        int rows = userMapper.insertUser(sysUser);

        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param editSysUser 用户信息
     * @return 结果
     */
    @Override
    public R updateUser(EditSysUser editSysUser) {
        SysUser user = userMapper.selectUserById(editSysUser.getUserId());
        if (user==null){
            return R.fail("未发现用户");
        }
        BeanProUtils.copyProperties(editSysUser,user);
        userMapper.updateUser(user);
        insertUserAuth(user.getUserId(),editSysUser.getRoleIds());
        return R.ok();
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public R insertUserAuth(Long userId, List<Long> roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
        return R.ok();
    }

    /**
     * 修改用户状态
     *
     * @param userStatus 用户信息
     * @return 结果
     */
    @Override
    public R updateUserStatus(EditUserStatus userStatus) {

        SysUser user = userMapper.selectUserById(userStatus.getUserId());
        if (user==null){
            return R.fail("未发现用户");
        }
        user.setStatus(userStatus.getStatus());
        return R.ok(userMapper.updateUser(user));
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param userPsd 用户信息
     * @return 结果
     */
    @Override
    public R resetPwd(EditUserPsd userPsd) {
        SysUser user=userMapper.selectUserById(userPsd.getUserId());
        if (user==null){
            return R.fail("未发现用户");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userMapper.resetUserPwdByUserId(user.getUserId(),user.getPassword()));
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }
//
//    /**
//     * 新增用户角色信息
//     *
//     * @param user 用户对象
//     */
//    @Override
//    public void insertUserRole(SysUser user) {
//        this.insertUserRole(user.getUserId(), user.getRoleIds());
//    }



    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, List<Long> roleIds) {
        if (QysStringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.size());
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }

            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);

        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {


        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);

        return userMapper.deleteUserByIds(userIds);
    }


    @Override
    public boolean isAdmin(Long userId) {

        return userId != null && 1L == userId;
    }
}
